package com.billjc.action;

import static com.opensymphony.xwork2.Action.ERROR;
import static com.opensymphony.xwork2.Action.INPUT;
import static com.opensymphony.xwork2.Action.SUCCESS;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.billjc.base.IbatisSessionFactory;
import com.billjc.model.Asset;
import com.opensymphony.xwork2.ActionSupport;

@Results( { @Result(name = SUCCESS, location = "/asset-list.jsp"),
		@Result(name = INPUT, location = "/asset-input.jsp") })
public class AssetAction extends ActionSupport {
	private static final long serialVersionUID = 1658262971384766077L;
	// protected static final String
	private Asset asset;
	List<Asset> assets = new ArrayList<Asset>();

	public String list() throws Exception {
		SqlSession session = IbatisSessionFactory.getSqlSessionFactory()
				.openSession();
		assets = session.selectList("account.selectAll");
		session.close();
		return SUCCESS;
	}

	@Action("update-queryById")
	public String input() {
		if (null != asset) {
			System.out.println("asset.getProblem_desc()"
					+ asset.getProblem_desc() + "asset.getId()="
					+ asset.getId());
		}
		SqlSession session = IbatisSessionFactory.getSqlSessionFactory()
				.openSession();
		asset = (Asset) session.selectOne("account.selectById", asset.getId());
		session.close();
		return INPUT;
	}

	public String excute() throws Exception {
		SqlSession session = IbatisSessionFactory.getSqlSessionFactory()
				.openSession();
		session.update("account.updateByAsset", asset);
		session.close();
		return list();
	}

	@SuppressWarnings("unchecked")
	public String fuzzyQuery() {
		SqlSession session = IbatisSessionFactory.getSqlSessionFactory()
				.openSession();
		String placed = null;
		String responsible = null;
		try {
			responsible = new String(asset.getResponsible_by().getBytes(
					"ISO-8859-1"), "utf-8");
			placed = new String(asset.getPlaced_at().getBytes("ISO-8859-1"),
					"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		asset.setResponsible_by(responsible);
		asset.setPlaced_at(placed);
		assets = session.selectList("account.fuzzyQueryByAsset_no", asset);
		session.close();
		return SUCCESS;
	}

	public Asset getAsset() {
		return asset;
	}

	public void setAsset(Asset asset) {
		this.asset = asset;
	}

	public List<Asset> getAssets() {
		return assets;
	}

	public void setAssets(List<Asset> assets) {
		this.assets = assets;
	}

}
